const highest = 27
const lowest = 18
const app = getApp()
const A = [23,-1,23,26]  // 日常
const B = [23,23,23,23]  // 居家
const C = [-1,-1,-1,-1]  // 离家
const tempatureArray = [A, B, C]

for(let x = 0; x < tempatureArray.length; x++) {
  for(let y = 0; y < tempatureArray[x].length; y++) {
    if(tempatureArray[x][y] < lowest || tempatureArray[x][y] > highest) {
      tempatureArray[x][y] = '-'
    }
  }
}

Page({
  data: {
    rangeArray: [],
    mode: '',
    on: false,
    screenWidth: 0,
    screenHeight: 0,
    temperatureRange: [],
    plan: []
  },

  onShow: function(e) {
    wx.getStorage({
      key: 'timeArray',
      success: res => {
        let tempTime = res.data
        let len = tempTime.length
        for(let i = 0; i < len; i++) {
          app.globalData.default[i].start = tempTime[i]
        }
      }
    })

    let tempRange = []
    for(let i = lowest; i <= highest; i++) {
      tempRange[i-lowest] = i
    }
    tempRange.unshift('无特殊要求')

    let name = app.globalData.name
    let selectedIndex = 0
    wx.getStorage({
      key: 'nameArray',
      success: res => {
        name = res.data
        wx.getStorage({
          key: 'selectedIndex',
          success: res => {
            selectedIndex = res.data
          }
        })
      },
      fail: err => {
        wx.getStorage({
          key: 'selectedIndex',
          success: res => {
            selectedIndex = res.data
          }
        })
      },
      complete: () => {
        wx.getStorage({
          key: 'plan' + name[selectedIndex],
          success: res => {
            this.setData({
              plan: res.data
            })
          },
          fail: err => {
            this.setData({
              plan: this.clone(app.globalData.default)
            })

            let value = selectedIndex
            if(value < tempatureArray.length) {
              for(let i = 0; i < tempatureArray[value].length; i++) {
                this.setData({
                  ['plan['+i+'].targetNormal']: tempatureArray[value][i],
                  ['plan['+i+'].targetWeekend']: tempatureArray[value][i]
                })
              }
            }
          },
          complete: () => {
            this.setData({
              mode: name[selectedIndex],
              rangeArray: name
            })
          }
        })
      }
    })

    this.setData({
      screenWidth: wx.getSystemInfoSync().windowWidth,
      screenHeight: wx.getSystemInfoSync().windowHeight,
      temperatureRange: tempRange
    })

    wx.getStorage({
      key: 'on',
      success: res => {
        this.setData({
          on: res.data
        })
      },
      fail: err => {
        this.setData({
          on: false
        })
      }
    })
  },

  autoChange: function(e) {
    wx.vibrateShort()
    
    wx.getStorage({
      key: 'plan' + this.data.rangeArray[e.detail.value],
      success: res => {
        this.setData({
          plan: res.data,
          mode: this.data.rangeArray[e.detail.value]
        })
      },
      fail: err => {
        this.setData({
          plan: this.clone(app.globalData.default),
          mode: this.data.rangeArray[e.detail.value]
        })

        let value = e.detail.value
        if(value < tempatureArray.length) {
          for(let i = 0; i < tempatureArray[value].length; i++) {
            this.setData({
              ['plan['+i+'].targetNormal']: tempatureArray[value][i],
              ['plan['+i+'].targetWeekend']: tempatureArray[value][i]
            })
          }
        }
      }
    })
  },

  on: function(e) {
    wx.vibrateShort()
    var flag = !this.data.on

    if(flag) {
      this.save()
      wx.setStorage({
        data: true,
        key: 'on',
      })
      for(let i = this.data.rangeArray.length - 1; i >= 0; i--) {
        if(this.data.rangeArray[i] == this.data.mode) {
          wx.setStorage({
            data: i,
            key: 'selectedIndex',
          })
          break;
        }
      }

      console.log('--auto ' + this.toString(this.data.plan))
      wx.request({
        url: getApp().globalData.myURL,
        data: {
          targetTemparture: '--auto ' + this.toString(this.data.plan)
        },
        success: res => {
          if(res.data.startsWith('success: ')) {
            console.log(res.data)
          }
          else {
            console.log('something wrong:', res.data)
          }
        },
        fail: err => {
          console.log(err)
        }
      })
    }
    else {
      wx.removeStorage({
        key: 'selectedIndex',
      })
      wx.setStorage({
        data: false,
        key: 'on',
      })

      wx.request({
        url: getApp().globalData.myURL,
        data: {
          targetTemparture: '--auto none'
        },
        success: res => {
          if(res.data.startsWith('success: ')) {
            console.log(res.data)
          }
          else {
            console.log('something wrong:', res.data)
          }
        },
        fail: err => {
          console.log(err)
        }
      })
    }
    this.setData({
      on: flag
    })

    wx.showToast({
      title: flag ? '方案已启用' : '方案已停用',
      icon: 'none'
    })
  },

  setTarget: function(e) {
    let index = e.currentTarget.dataset.index
    let type = e.currentTarget.dataset.type == '0' ? 'Normal' : 'Weekend'
    let value = parseInt(e.detail.value) + parseInt(lowest) - 1
    if(value < lowest || value > highest) value = '-'
    let str = 'plan[' + index + '].target' + type
    this.setData({
      [str]: value
    })
  },

  setTime: function(e) {
    let index = e.currentTarget.dataset.index
    let value = e.detail.value
    let str = 'plan[' + index + '].start'
    this.setData({
      [str]: value
    })
  },

  save: function(e) {
    let tempPlan = this.clone(this.data.plan)
    tempPlan.sort(function(a, b) {
      if(a.start < b.start) return -1;
      else return 1;
    })

    let len = tempPlan.length
    for(let i = 1; i < len; i++) {
      if(tempPlan[i-1].start >= tempPlan[i].start) {
        this.show('存在时间段冲突')
        return
      }
    }

    this.setData({
      plan: tempPlan
    })

    wx.setStorage({
      data: this.data.plan,
      key: 'plan' + this.data.mode,
      success: res => {
        wx.showToast({
          title: '保存成功',
        })
      }
    })
  },

  show: function(info) {
    wx.showToast({
      title: info,
      icon: 'none'
    })
  },

  feedback: function(e) {
    wx.vibrateShort()
  },

  clone: function(obj) {
    var another = []

    let len = obj.length
    for(let i = 0; i < len; i++) {
      var temp = {}
      temp.start = obj[i].start
      temp.end = obj[i].end
      temp.targetNormal = obj[i].targetNormal
      temp.targetWeekend = obj[i].targetWeekend
      another[i] = temp
    }

    return another
  },

  toString: function(myPlan) {
    var str = ''

    for(let i = 0; i < myPlan.length; i++) {
      str += myPlan[i].start + '*' + myPlan[i].targetNormal + '*' + myPlan[i].targetWeekend

      if(i+1 < myPlan.length) str += ','
    }

    return str
  }
})